using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace DocumentCreationSystem.Models
{
    /// <summary>
    /// 增强的用户意图
    /// </summary>
    public class EnhancedUserIntent
    {
        /// <summary>
        /// 原始用户请求
        /// </summary>
        public string OriginalRequest { get; set; } = string.Empty;

        /// <summary>
        /// 复杂意图分析结果
        /// </summary>
        public object ComplexIntent { get; set; } = new();

        /// <summary>
        /// 项目上下文
        /// </summary>
        public ProjectContext? ProjectContext { get; set; }

        /// <summary>
        /// 是否需要角色规划
        /// </summary>
        public bool RequiresCharacterPlanning { get; set; }

        /// <summary>
        /// 是否需要工作流规划
        /// </summary>
        public bool RequiresWorkflowPlanning { get; set; }

        /// <summary>
        /// 规划范围
        /// </summary>
        public PlanningScope PlanningScope { get; set; }

        /// <summary>
        /// 分析时间
        /// </summary>
        public DateTime AnalyzedAt { get; set; }
    }

    // ProjectContext 已在 IntelligentTaskModels.cs 中定义

    /// <summary>
    /// 规划范围枚举
    /// </summary>
    public enum PlanningScope
    {
        Task,       // 单个任务
        Content,    // 内容创作
        Project,    // 整个项目
        System      // 系统级别
    }

    /// <summary>
    /// 综合规划方案
    /// </summary>
    public class ComprehensivePlan
    {
        /// <summary>
        /// 规划ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 用户意图
        /// </summary>
        public EnhancedUserIntent UserIntent { get; set; } = new();

        /// <summary>
        /// 角色规划
        /// </summary>
        public CharacterPlan? CharacterPlan { get; set; }

        /// <summary>
        /// 工作流规划
        /// </summary>
        public WorkflowPlan? WorkflowPlan { get; set; }

        /// <summary>
        /// 优化说明
        /// </summary>
        public string? OptimizationNotes { get; set; }

        /// <summary>
        /// 是否已优化
        /// </summary>
        public bool IsOptimized { get; set; }

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; }

        /// <summary>
        /// 预估执行时间
        /// </summary>
        public TimeSpan EstimatedExecutionTime { get; set; }
    }

    /// <summary>
    /// 角色规划
    /// </summary>
    public class CharacterPlan
    {
        /// <summary>
        /// 规划ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 角色列表
        /// </summary>
        public List<PlannedCharacter> Characters { get; set; } = new();

        /// <summary>
        /// 角色关系网络
        /// </summary>
        public List<CharacterRelationship> Relationships { get; set; } = new();

        /// <summary>
        /// 角色发展轨迹
        /// </summary>
        public List<CharacterDevelopmentPath> DevelopmentPaths { get; set; } = new();

        /// <summary>
        /// 规划策略
        /// </summary>
        public CharacterPlanningStrategy Strategy { get; set; } = new();

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; }
    }

    /// <summary>
    /// 规划的角色
    /// </summary>
    public class PlannedCharacter
    {
        /// <summary>
        /// 角色ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 角色名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 角色类型
        /// </summary>
        public CharacterType Type { get; set; }

        /// <summary>
        /// 角色描述
        /// </summary>
        public string Description { get; set; } = string.Empty;

        /// <summary>
        /// 角色属性
        /// </summary>
        public Dictionary<string, object> Attributes { get; set; } = new();

        /// <summary>
        /// 角色技能
        /// </summary>
        public List<string> Skills { get; set; } = new();

        /// <summary>
        /// 角色装备
        /// </summary>
        public List<string> Equipment { get; set; } = new();

        /// <summary>
        /// 重要程度
        /// </summary>
        public CharacterImportance Importance { get; set; }

        /// <summary>
        /// 出场章节
        /// </summary>
        public List<int> AppearanceChapters { get; set; } = new();
    }

    /// <summary>
    /// 角色关系
    /// </summary>
    public class CharacterRelationship
    {
        public string FromCharacterId { get; set; } = string.Empty;
        public string ToCharacterId { get; set; } = string.Empty;
        public RelationshipType Type { get; set; }
        public string Description { get; set; } = string.Empty;
        public int Strength { get; set; } // 关系强度 1-10
    }

    /// <summary>
    /// 角色发展路径
    /// </summary>
    public class CharacterDevelopmentPath
    {
        public string CharacterId { get; set; } = string.Empty;
        public List<DevelopmentMilestone> Milestones { get; set; } = new();
        public string DevelopmentTheme { get; set; } = string.Empty;
    }

    /// <summary>
    /// 发展里程碑
    /// </summary>
    public class DevelopmentMilestone
    {
        public int ChapterNumber { get; set; }
        public string Event { get; set; } = string.Empty;
        public Dictionary<string, object> AttributeChanges { get; set; } = new();
        public List<string> NewSkills { get; set; } = new();
    }

    /// <summary>
    /// 工作流规划
    /// </summary>
    public class WorkflowPlan
    {
        /// <summary>
        /// 规划ID
        /// </summary>
        public string Id { get; set; } = Guid.NewGuid().ToString();

        /// <summary>
        /// 工作流步骤
        /// </summary>
        public List<PlannedWorkflowStep> Steps { get; set; } = new();

        /// <summary>
        /// 执行策略
        /// </summary>
        public WorkflowExecutionStrategy Strategy { get; set; } = new();

        /// <summary>
        /// 依赖关系
        /// </summary>
        public List<StepDependency> Dependencies { get; set; } = new();

        /// <summary>
        /// 并行执行组
        /// </summary>
        public List<ParallelExecutionGroup> ParallelGroups { get; set; } = new();

        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedAt { get; set; }
    }

    /// <summary>
    /// 规划的工作流步骤
    /// </summary>
    public class PlannedWorkflowStep
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public WorkflowStepType Type { get; set; }
        public Dictionary<string, object> Parameters { get; set; } = new();
        public TimeSpan EstimatedDuration { get; set; }
        public int Priority { get; set; }
        public List<string> RequiredResources { get; set; } = new();
        public List<string> OutputArtifacts { get; set; } = new();
    }

    /// <summary>
    /// 步骤依赖
    /// </summary>
    public class StepDependency
    {
        public string FromStepId { get; set; } = string.Empty;
        public string ToStepId { get; set; } = string.Empty;
        public DependencyType Type { get; set; }
        public string? Condition { get; set; }
    }

    /// <summary>
    /// 并行执行组
    /// </summary>
    public class ParallelExecutionGroup
    {
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public List<string> StepIds { get; set; } = new();
        public int MaxConcurrency { get; set; } = 3;
    }

    /// <summary>
    /// 规划执行结果
    /// </summary>
    public class PlanExecutionResult
    {
        public ComprehensivePlan Plan { get; set; } = new();
        public ExecutionStatus Status { get; set; }
        public DateTime StartedAt { get; set; }
        public DateTime? CompletedAt { get; set; }
        public string? ErrorMessage { get; set; }
        public CharacterExecutionResult? CharacterExecutionResult { get; set; }
        public WorkflowExecutionResult? WorkflowExecutionResult { get; set; }
        public List<ExecutionLog> Logs { get; set; } = new();
    }

    /// <summary>
    /// 角色执行结果
    /// </summary>
    public class CharacterExecutionResult
    {
        public List<Character> CreatedCharacters { get; set; } = new();
        public List<string> UpdatedCharacters { get; set; } = new();
        public Dictionary<string, object> Metrics { get; set; } = new();
    }

    /// <summary>
    /// 工作流执行结果
    /// </summary>
    public class WorkflowExecutionResult
    {
        public List<StepExecutionResult> StepResults { get; set; } = new();
        public Dictionary<string, object> Outputs { get; set; } = new();
        public Dictionary<string, object> Metrics { get; set; } = new();
    }

    /// <summary>
    /// 步骤执行结果
    /// </summary>
    public class StepExecutionResult
    {
        public string StepId { get; set; } = string.Empty;
        public ExecutionStatus Status { get; set; }
        public DateTime StartedAt { get; set; }
        public DateTime? CompletedAt { get; set; }
        public string? Output { get; set; }
        public string? ErrorMessage { get; set; }
    }

    /// <summary>
    /// 自主规划最终结果
    /// </summary>
    public class AutonomousPlanResult
    {
        public PlanExecutionResult ExecutionResult { get; set; } = new();
        public MonitoringResult MonitoringResult { get; set; } = new();
        public List<OptimizationSuggestion> OptimizationSuggestions { get; set; } = new();
        public bool Success { get; set; }
        public bool OptimizationsApplied { get; set; }
        public DateTime CompletedAt { get; set; }
        public string Summary { get; set; } = string.Empty;
    }

    /// <summary>
    /// 监控结果
    /// </summary>
    public class MonitoringResult
    {
        public PerformanceMetrics PerformanceMetrics { get; set; } = new();
        public QualityMetrics QualityMetrics { get; set; } = new();
        public List<string> Issues { get; set; } = new();
        public List<string> Recommendations { get; set; } = new();
    }

    /// <summary>
    /// 性能指标
    /// </summary>
    public class PerformanceMetrics
    {
        public TimeSpan ExecutionTime { get; set; }
        public int TasksCompleted { get; set; }
        public int TasksFailed { get; set; }
        public double SuccessRate { get; set; }
        public Dictionary<string, object> AdditionalMetrics { get; set; } = new();
    }

    /// <summary>
    /// 质量指标
    /// </summary>
    public class QualityMetrics
    {
        public double ContentQuality { get; set; }
        public double ConsistencyScore { get; set; }
        public double CompletenessScore { get; set; }
        public Dictionary<string, double> DetailedScores { get; set; } = new();
    }

    // OptimizationSuggestion 已在 AdvancedAIAgentModels.cs 中定义

    /// <summary>
    /// 执行上下文
    /// </summary>
    public class ExecutionContext
    {
        public ComprehensivePlan Plan { get; set; } = new();
        public string? ProjectId { get; set; }
        public string ExecutionId { get; set; } = string.Empty;
        public Dictionary<string, object> Variables { get; set; } = new();
        public CancellationToken CancellationToken { get; set; }
    }

    /// <summary>
    /// 执行日志
    /// </summary>
    public class ExecutionLog
    {
        public DateTime Timestamp { get; set; }
        public PlanningLogLevel Level { get; set; }
        public string Message { get; set; } = string.Empty;
        public string? StepId { get; set; }
        public Dictionary<string, object> Data { get; set; } = new();
    }

    // 枚举定义
    public enum CharacterType { Protagonist, Antagonist, Supporting, Background }
    public enum CharacterImportance { Primary, Secondary, Tertiary, Background }
    public enum RelationshipType { Family, Friend, Enemy, Mentor, Student, Ally, Rival, Romantic }
    public enum WorkflowStepType { Analysis, Generation, Validation, Integration, Output, AIGeneration, FileOperation, DataProcessing }
    public enum DependencyType { Sequential, Conditional, Resource, FinishToStart }
    public enum ExecutionStatus { Pending, Running, Completed, Failed, Cancelled }
    // OptimizationType 和 OptimizationPriority 已在 AdvancedAIAgentModels.cs 中定义
    public enum PlanningLogLevel { Debug, Info, Warning, Error }

    /// <summary>
    /// 角色规划策略
    /// </summary>
    public class CharacterPlanningStrategy
    {
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public Dictionary<string, object> Parameters { get; set; } = new();
    }

    /// <summary>
    /// 工作流执行策略
    /// </summary>
    public class WorkflowExecutionStrategy
    {
        public string Name { get; set; } = string.Empty;
        public ExecutionMode Mode { get; set; }
        public int MaxConcurrency { get; set; } = 3;
        public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes(30);
        public bool EnableRetry { get; set; } = true;
        public int MaxRetries { get; set; } = 3;
    }

    public enum ExecutionMode { Sequential, Parallel, Adaptive }

    /// <summary>
    /// 角色规划意图
    /// </summary>
    public class CharacterPlanningIntent
    {
        public DateTime DetectedAt { get; set; }
        public double Confidence { get; set; }
        public CharacterPlanningType PlanningType { get; set; }
        public List<string> TargetCharacters { get; set; } = new();
        public CharacterPlanningScope PlanningScope { get; set; }
        public List<string> RequiredAttributes { get; set; } = new();
    }

    /// <summary>
    /// 工作流规划意图
    /// </summary>
    public class WorkflowPlanningIntent
    {
        public DateTime DetectedAt { get; set; }
        public double Confidence { get; set; }
        public WorkflowPlanningType PlanningType { get; set; }
        public WorkflowExecutionMode ExecutionMode { get; set; }
        public WorkflowPlanningScope TargetScope { get; set; }
        public List<string> RequiredSteps { get; set; } = new();
    }

    // 枚举定义
    public enum CharacterPlanningType { Creation, Relationship, Development, Analysis, General }
    public enum CharacterPlanningScope { Individual, Major, All, Relevant }
    public enum WorkflowPlanningType { Automation, Batch, Sequential, Parallel, Monitoring, General }
    public enum WorkflowPlanningScope { Task, Content, Project, Custom }
    public enum WorkflowExecutionMode { Sequential, Parallel, Adaptive }

    /// <summary>
    /// 执行会话
    /// </summary>
    public class ExecutionSession
    {
        public string Id { get; set; } = string.Empty;
        public ComprehensivePlan Plan { get; set; } = new();
        public ExecutionContext Context { get; set; } = new();
        public DateTime StartTime { get; set; }
        public DateTime? EndTime { get; set; }
        public DateTime LastUpdateTime { get; set; }
        public ExecutionSessionStatus Status { get; set; }
        public AdaptiveExecutionSettings AdaptiveSettings { get; set; } = new();
        public List<ExecutionProgressUpdate> ProgressUpdates { get; set; } = new();
        public List<ExecutionException> Exceptions { get; set; } = new();
        public List<ExecutionAdjustment> Adjustments { get; set; } = new();
        public List<RecoveryAction> RecoveryActions { get; set; } = new();
        public PlanExecutionResult? FinalResult { get; set; }
    }

    /// <summary>
    /// 自适应执行设置
    /// </summary>
    public class AdaptiveExecutionSettings
    {
        public int MaxRetryAttempts { get; set; } = 3;
        public double RetryDelayMultiplier { get; set; } = 2.0;
        public double PerformanceThreshold { get; set; } = 0.8;
        public double ErrorRateThreshold { get; set; } = 0.1;
        public AdaptationSensitivity AdaptationSensitivity { get; set; } = AdaptationSensitivity.Medium;
    }

    /// <summary>
    /// 执行进度更新
    /// </summary>
    public class ExecutionProgressUpdate
    {
        public DateTime Timestamp { get; set; }
        public ProgressUpdateType Type { get; set; }
        public string Message { get; set; } = string.Empty;
        public string? StepId { get; set; }
        public double? ProgressPercentage { get; set; }
        public ResourceUsageInfo? ResourceUsage { get; set; }
        public Dictionary<string, object> AdditionalData { get; set; } = new();
    }

    /// <summary>
    /// 执行异常
    /// </summary>
    public class ExecutionException
    {
        public DateTime Timestamp { get; set; }
        public ExecutionExceptionType Type { get; set; }
        public string Message { get; set; } = string.Empty;
        public string? StepId { get; set; }
        public string? StackTrace { get; set; }
        public bool IsRecoverable { get; set; } = true;
        public Dictionary<string, object> Context { get; set; } = new();
    }

    /// <summary>
    /// 调整分析
    /// </summary>
    public class AdjustmentAnalysis
    {
        public bool IsNeeded { get; set; }
        public AdjustmentReasonCode ReasonCode { get; set; }
        public AdjustmentSeverity Severity { get; set; }
        public string? AIRecommendation { get; set; }
        public Dictionary<string, object> AnalysisData { get; set; } = new();
    }

    /// <summary>
    /// 执行调整
    /// </summary>
    public class ExecutionAdjustment
    {
        public DateTime Timestamp { get; set; }
        public AdjustmentReasonCode ReasonCode { get; set; }
        public AdjustmentSeverity Severity { get; set; }
        public List<string> Actions { get; set; } = new();
        public bool WasSuccessful { get; set; } = true;
        public string? Notes { get; set; }
    }

    /// <summary>
    /// 恢复动作
    /// </summary>
    public class RecoveryAction
    {
        public DateTime Timestamp { get; set; } = DateTime.Now;
        public RecoveryActionType Type { get; set; }
        public int MaxAttempts { get; set; } = 3;
        public TimeSpan DelayBetweenAttempts { get; set; } = TimeSpan.FromSeconds(5);
        public bool WasSuccessful { get; set; }
        public string? ErrorMessage { get; set; }
    }

    /// <summary>
    /// 资源使用信息
    /// </summary>
    public class ResourceUsageInfo
    {
        public double CpuUsage { get; set; }
        public double MemoryUsage { get; set; }
        public double DiskUsage { get; set; }
        public double NetworkUsage { get; set; }
        public Dictionary<string, double> CustomMetrics { get; set; } = new();
    }

    /// <summary>
    /// 执行会话摘要
    /// </summary>
    public class ExecutionSessionSummary
    {
        public string SessionId { get; set; } = string.Empty;
        public DateTime StartTime { get; set; }
        public DateTime EndTime { get; set; }
        public ExecutionSessionStatus Status { get; set; }
        public int TotalAdjustments { get; set; }
        public int TotalRecoveryActions { get; set; }
        public double FinalPerformanceScore { get; set; }
        public double FinalErrorRate { get; set; }
        public string PerformanceAnalysis { get; set; } = string.Empty;
        public List<string> RecommendationsForFuture { get; set; } = new();
    }

    // 新增枚举
    public enum ExecutionSessionStatus { Running, Paused, Completed, Failed, Cancelled }
    public enum AdaptationSensitivity { Low, Medium, High }
    public enum ProgressUpdateType { StepStarted, StepCompleted, StepFailed, HealthCheck, ResourceUpdate }
    public enum ExecutionExceptionType { NetworkTimeout, ResourceExhausted, InvalidInput, SystemError, Unknown }
    public enum AdjustmentReasonCode { PerformanceDegradation, HighErrorRate, ResourceConstraint, UserRequest }
    public enum AdjustmentSeverity { Low, Medium, High, Critical }
    public enum RecoveryActionType { Retry, RetryWithDelay, ReduceLoad, SkipAndContinue, Restart }
    public enum PlanComplexity { Simple, Medium, Complex, VeryComplex }
}
